import React from 'react';
import {
  View,
  WebView,
  ScrollView,
  Text,
  TouchableOpacity,
  Platform,
  Image,
  TextInput,
  Keyboard,
  Alert,
  Switch,
} from 'react-native';

import TImage from '../../components/TImage';
import NewsConstants from '../../common/NewsConstants';
import Constants from '../../common/Constants';
import SizeUtils from '../../common/SizeUtils';
import PostContentPage from '../post/PostContentPage';
import {DateUtils,HtmlUtils} from '../../utils/Utils';
import WH_RequestContentAction from '../../actions/workhard/WH_RequestContentAction';
import WH_RequestCommentListAction from '../../actions/workhard/WH_RequestCommentListAction';
import WH_RequestOfficialPostsAction from '../../actions/workhard/WH_RequestOfficialPostsAction';
import WH_RequestOfficialAction from '../../actions/workhard/WH_RequestOfficialAction';
import WH_IdeasVoteAction from '../../actions/workhard/WH_IdeasVoteAction';
import WH_Constants from './WH_Constants';
import ToastUtils from '../../common/ToastUtils';

const CONTENT_MIN_HEIGHT = 144;
export default class WH_PostContentPage extends PostContentPage {
  constructor(props) {
    super(props);
    this._sendRequest = false;
    this.state.keyboardHeight=0;
    this.keyboardDidShowListener = Keyboard.addListener('keyboardDidShow', this._keyboardDidShow.bind(this));
    this.keyboardDidHideListener = Keyboard.addListener('keyboardDidHide', this._keyboardDidHide.bind(this));
  }
  componentWillUpdate(nextProps, nextStates) {
    super.componentWillUpdate(nextProps, nextStates);
    const {isZhuanjia,official} = this.props.pageData.routeData;
    const isShowZhuanjia = (isZhuanjia===true&&official===0)?true:false;
    if(isShowZhuanjia&& nextStates.viewStatus == 3 && this._sendRequest) {
      nextStates.content='';
      this._sendRequest = false;
      Alert.alert('提示','回复成功',[
          {text:'确定',onPress:()=>{this.goBack()}}
        ])
    }
    else if(isShowZhuanjia&&nextStates.viewStatus == 4 && this._sendRequest) {
      this._sendRequest = false;
      nextStates.viewStatus = 1;
      Alert.alert('提示','回复失败',[
          {text:'确定'}
        ])
    }
    if (nextStates.needVote) {
      nextStates.needVote=false;
      Alert.alert('提示',nextStates.viewStatus == 93?'投票成功':'投票失败',[
          {text:'确定',onPress:()=>{this.goBack()}}
        ])
    }
    return true;
  }
  _dealEnterPage() {
    this._initShowTag();
    this.setState({
      officdata:{} 
    });
  }
  _initShowTag() {
    super._initShowTag();
    const {isZhuanjia,official,isPing} = this.props.pageData.routeData;
    const isShowZhuanjia = (isZhuanjia===true&&official===0)?true:false;
    if (isPing) {
      this._showFooterBar = false;
      this._showCommentAfterContent = false;
      this._showTag = false;
      this._showZan = false;
      this._showImages = false;
    }else{
      this._showCommentAfterContent = isShowZhuanjia?false:true;
      this._showFooterBar = isShowZhuanjia?false:true;
      this._showTag = true;
      this._showImages = true;
    }
  }

  _getTabText() {
    return WH_Constants.getTypeDataBySubTag(this.state.postData.sub_tag);
  }
  _renderButtonView(){
    return(
      <TouchableOpacity style={{
          width:(SizeUtils.getWindowSize.width - SizeUtils.translateDesignWidthToCode(40)),
          backgroundColor:'#ee3535',
          justifyContent: 'center',
          alignItems: 'center',
          height: SizeUtils.translateDesignHeightToCode(88),
        }} onPress={()=>{this._submit()}}>
        <Text style={{fontSize:SizeUtils.translateFontSizeToCode(30),color:'#fff'}}>{'提交'}</Text>
      </TouchableOpacity>
    );
  }
  _keyboardDidShow(e){
    if(e.endCoordinates){
         this.setState({
          keyboardHeight:e.endCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }else if(e.startCoordinates){
        this.setState({
          keyboardHeight:e.startCoordinates.height,
      }, ()=> {
        this._scrollToEnd();
      })
    }
  }
  _scrollToEnd() {
    setTimeout(()=>{
      this._scrollView.scrollToEnd();
    }, 500);
  }
  _keyboardDidHide(e){
      this.setState({
          keyboardHeight:0
      }, ()=> {
        setTimeout(()=>{
          this._scrollView.scrollTo({y:0});
        }, 500);
      })
  }
  _submit(){
    if(!this.state.content||this.state.content === ""){
       ToastUtils.show("请输入回复内容");
    }
    if(this._sendRequest){
      return;
    }
    new WH_RequestOfficialPostsAction().call(this, {
     post_id:this.props.pageData.routeData.post_id,
     content:this.state.content,
     recommend:this.state.recommend?1:0,
     official:this.state.oficial?1:0,
     tip:this.state.tip||0
    });
    this._sendRequest = true;
  }
  changeSwitch(switchName, value) {
    const newState = {};
    newState[switchName] = value;
    this.setState(newState);
  }
  _onPressWriteButton(isYes){
    Alert.alert('', isYes?'确定投票':'确定弃权', [
        { text: '确定', onPress: () => {
          new WH_IdeasVoteAction().call(this, {
            post_id:this.props.pageData.routeData.post_id,
            type:this.props.pageData.routeData.pingType,
            vote:isYes?1:2
          });
        }},
        {text: '取消', onPress: () => {}, style: 'cancel'},
    ])
  }
  _getZanImageSource() {
    if(this.state.is_liked == 1) {
      return require("../../../resource/images/common/dianzan.png");
    }
    else {
      return require("../../../resource/images/common/dianzanr.png");
    }
  }
  _renderZanView(){
    if(this._showZan === false) {
      return;
    }
    return(
      <View style={{
        height:SizeUtils.translateDesignHeightToCode(100),
        alignItems: 'center',justifyContent: 'center',
      }}>
        <TouchableOpacity onPress={this._onPressLikeBtn.bind(this)} style={{
          width:SizeUtils.translateDesignWidthToCode(200),
          height:SizeUtils.translateDesignHeightToCode(60),
          borderRadius:SizeUtils.translateDesignHeightToCode(60),
          borderWidth:0.5,
          borderColor:this.state.is_liked == 1?'#ee3535':'#e3e3e3',
          justifyContent: 'center',alignItems: 'center',
          flexDirection:'row',
        }}>
          <TImage source={this._getZanImageSource()}
              style={{width:34, height:34}}/>
            <Text style={{marginLeft:5,color:this.state.is_liked == 1?'#ee3535':'#e3e3e3',fontSize:SizeUtils.translateFontSizeToCode(22)}}>{this._getLinkNum()}
            </Text>
        </TouchableOpacity>
      </View>
    );
  }
  _renderAfterContent() {
    const {isZhuanjia,official,isPing} = this.props.pageData.routeData;
    if (isPing) {
      return(
        <View style={{width:SizeUtils.getWindowSize().width,height:SizeUtils.translateDesignHeightToCode(110)}} />
      )
    }
    const isShowZhuanjia = (isZhuanjia===true&&official===0)?true:false;
    if (isShowZhuanjia) {
      const { oficial, recommend } = this.state;
      return(
      <View>
      <TextInput
        style={{padding:0,height: SizeUtils.translateDesignHeightToCode(400),
          borderColor: '#f2f2f2', borderBottomWidth: 1,
          backgroundColor:'#fff',
          paddingLeft: SizeUtils.translateDesignHeightToCode(20),
          paddingTop: SizeUtils.translateDesignHeightToCode(20),
          textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
        onChangeText = {(content) => this.setState({content})}
        placeholder = "请输入回复的内容"
        multiline = {true}
        underlineColorAndroid="transparent"
        value = {this.state.content}
        ref = 'contentRef'
        maxLength={700}
      />
        <SwitchButton
          title={"专家推荐"}
          onValueChange={value => this.changeSwitch("oficial", value)}
          value={oficial}
        />
        {/**<SwitchButton
          title={"重要回复"}
          onValueChange={value => this.changeSwitch("recommend", value)}
          value={recommend}
        />
        <View style={{
          padding:0,height: SizeUtils.translateDesignHeightToCode(90),
              borderColor: '#f2f2f2', borderBottomWidth: 1,
              backgroundColor:'#fff',
              paddingLeft:15,
              flexDirection:'row',
              alignItems: 'center',
        }}>
          <Text style={{fontSize:SizeUtils.translateFontSizeToCode(28),}}>打赏金额: </Text>
          <TextInput
            style={{
              flex:1,
              textAlignVertical: "top", fontSize: SizeUtils.translateFontSizeToCode(30)}}
            onChangeText = {(content) => this.setState({tip:content})}
            placeholder = "请输入打赏金额"
            multiline = {false}
            underlineColorAndroid="transparent"
            value = {this.state.tip}
            maxLength={10}
          />
        </View>**/}
        {this._renderButtonView()}
        <View style={{width:SizeUtils.getWindowSize().width, height:this.state.keyboardHeight,}} />
      </View>
    )
    }
    return (
      <View style={{width:(SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80)),paddingLeft:20
        }}>
        {this.state.officdata&&this.state.officdata.content?
          <View style={{backgroundColor:'#fff',
          paddingBottom:SizeUtils.translateDesignHeightToCode(30),
          paddingTop:SizeUtils.translateDesignHeightToCode(30)}}>
            <View style={{flexDirection:"row",alignItems: 'center',justifyContent: 'space-between',}}>
              <Text style={{fontSize:14,color:'#ee3535',}}>官方回复</Text>
              <Text style={{fontSize:12,color:'#000',}}>{"发布时间: " + DateUtils.formatOffocile(this.state.officdata.updated_at)}</Text>
            </View>
            <Text style={{fontSize:14,color:'#ee3535',marginTop:8}}>{this.state.officdata.content}</Text>
          </View>:null
        }
        {this._renderMoney()}
      </View>
    )
  }
  _getContent(postData){
    let content = "加载中...";
    let hasContent = false;
    if(postData.content && postData.content.indexOf("http") != 0) {
      if(this._saveContentPre === postData.content) {
        content = this._saveContentAfter;
      }
      else {
        content = HtmlUtils.contentFormatImg(postData.content);
      }
      hasContent = true;
    }
    else if(this.state.urlData != ""){
      if(this._saveContentPre === this.state.urlData) {
        content = this._saveContentAfter;
      }
      else {
        content = HtmlUtils.contentFormatImg(this.state.urlData);
      }
      hasContent = true;
    }
    this._saveContentPre = postData.content;
    this._saveContentAfter = content;

    if(hasContent) {
      var arr = content.split('&');
      if (arr.length===3) {
          content = `<div style="font-size:22px">` + '问题的提出:' + `</div>`;
          content += `<div style="font-size:18px;margin-left:10px;margin-top:4px;color:#999">` + arr[0] + `</div>`;
          content += `<div style="font-size:22px;margin-top:4px;">` + '解决办法:' + `</div>`;
          content += `<div style="font-size:18px;margin-left:10px;margin-top:4px;color:#999">` + arr[1] + `</div>`;
          content += `<div style="font-size:22px;margin-top:4px;">` + '可预见效果:' + `</div>`;
          content += `<div style="font-size:18px;margin-left:10px;margin-top:4px;color:#999">` + arr[2] + `</div>`;
      }else{
        content = `<div style="font-size:20px">` + content + `</div>`;
      }
      content = HtmlUtils.contentFontSizeScale(content, this.state.changeFontSize)
    }
    else {
      content = `<div style="font-size:14px;text-align='center'">` + content + `</div>`;
    }
    return content;
  }
  _tipNumber(data){
    if (data.tip_year>0) {
      return data.tip_year;
    }
    if (data.tip_month>0) {
      return data.tip_month;
    }
    return 0;
  }
  _renderMoney() {
    const tip  = this._tipNumber(this.props.pageData.routeData);
    if(tip <= 0) {
      return;
    }
    return (
      <View style={{width:(SizeUtils.getWindowSize().width - SizeUtils.translateDesignWidthToCode(80)),
        height:SizeUtils.translateDesignHeightToCode(106),
        paddingTop:SizeUtils.translateDesignHeightToCode(40),
        borderColor:"#4682fa", borderLeftWidth:SizeUtils.translateDesignNumToCode(8)}}>
        <Text style={{color:"#4682fa", paddingLeft:SizeUtils.translateDesignWidthToCode(70),
          fontSize:SizeUtils.translateFontSizeToCode(34)}}>
          本文已获得 {tip} 元现金奖励
        </Text>
      </View>
    )
  }

  _sendRequestDataAction() {
    new WH_RequestContentAction().call(this, {post_id:this.props.pageData.routeData.post_id});
    new WH_RequestOfficialAction().call(this, {post_id:this.props.pageData.routeData.post_id});
  }

  _getModuleType() {
    return Constants.MODULE_TYPE.WORK_HARD;
  }

  _sendRequestCommentListAction(page = 1) {
    let data = {page:page, page_size:10, post_id:this.props.pageData.routeData.post_id};
    new WH_RequestCommentListAction().call(this, data);
  }
}

const SwitchButton = ({ title, onValueChange, disabled, value, style }) => {
  return (
    <View
      style={[
        {
          paddingHorizontal: SizeUtils.translateDesignWidthToCode(28),
          height: SizeUtils.translateDesignHeightToCode(86),
          flexDirection: "row",
          alignItems: "center",
          borderBottomWidth: SizeUtils.translateDesignNumToCode(3),
          borderColor: "#f2f2f2"
        },
        style
      ]}
    >
      <View>
        <Text
          style={{
            fontSize: SizeUtils.translateFontSizeToCode(28),
            color: "#000000"
          }}
        >
          {title}
        </Text>
      </View>
      <View
        style={{
          flex: 1,
          alignItems: "flex-end"
        }}
      >
        <Switch
          style={{ backgroundColor: "transparent" }}
          disabled={disabled}
          onTintColor="#4cd964"
          onValueChange={onValueChange}
          value={value}
        />
      </View>
    </View>
  );
};
